package tech.mhuang.pacebox.core.exception;

import tech.mhuang.pacebox.core.util.ObjectUtil;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 异常工具类
 *
 * @author mhuang
 * @since 1.0.0
 */
public class ExceptionUtil {

    /**
     * 获得完整消息，包括异常名
     *
     * @param e 异常
     * @return 完整消息
     */
    public static String getMessage(Throwable e) {
        if (ObjectUtil.isEmpty(e)) {
            return null;
        }
        return String.format("%s:%s", e.getClass().getSimpleName(), e.getMessage());
    }

    public static Map<String, String> logsForException(Throwable throwable) {
        Map<String, String> errorLog = new HashMap<>(3);
        String message = throwable.getCause() != null ? throwable.getCause().getMessage() : throwable.getMessage();
        if (message != null) {
            errorLog.put("message", message);
        }
        StringWriter sw = new StringWriter();
        throwable.printStackTrace(new PrintWriter(sw));
        errorLog.put("stack", sw.toString());

        return errorLog;
    }
}
